package cn.zimo.cityinhand.lawregulation;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.zimo.cityinhand.R;
import cn.zimo.cityinhand.TitleBar;
import cn.zimo.cityinhand.utils.FileChooseUtils;
import cn.zimo.cityinhand.utils.MDFonts;
import cn.zimo.cityinhand.utils.MDFontsUtils;

public class LawsRegulations extends TitleBar {
    private TextView tv_fileUploadimg;
    private LinearLayout ll_upload;
    private ListView lv_filesName;
    private List<File> fileList = new ArrayList<>();
    private fileListAdapter adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_laws_regulations);
        initView();
    }
    //////////////////各项初始化///////////////////////////////
    private void initView(){
        initTitleBar();
        setTitle("法律法规");
        invisibleForward();

        lv_filesName = findViewById(R.id.lv_filesName);
        tv_fileUploadimg = findViewById(R.id.tv_fileUploadimg);
        ll_upload = findViewById(R.id.ll_uploadfile);

        //上传文件图片设定
        tv_fileUploadimg.setText(MDFonts.Plus);
        tv_fileUploadimg.setTextColor(Color.WHITE);
        tv_fileUploadimg.setTextSize(30);
        MDFontsUtils.setOcticons(tv_fileUploadimg);
        findFiles();

        /////////////////点击上传事件/////////////////////////////
        ll_upload.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    ll_upload.setBackgroundColor(Color.rgb(51,102,51));
                }
                if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    ll_upload.setBackgroundColor(Color.rgb(153,204,102));
                    //选择文件
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("application/pdf");
                    startActivityForResult(intent,1);

                }
                return true;
            }
        });

        adapter = new fileListAdapter();
        lv_filesName.setAdapter(adapter);
        lv_filesName.setOnItemClickListener(new fileChoose());

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_OK){
            Uri uri = data.getData();
            String path = FileChooseUtils.getFilePathByURI(this,uri);
            path = path.substring(path.indexOf(":") + 1,path.length());
            File file = new File(path);// 这里不需要手动加入sdPath了
            String filename = path.substring(path.lastIndexOf("/") + 1,path.length());

            Log.i("path:" ,path);
            Log.i("filename",filename);

            BufferedInputStream reader = null;
            BufferedOutputStream writer = null;
            try {
                reader = new BufferedInputStream(new FileInputStream(file));
                writer = new BufferedOutputStream(new FileOutputStream(sdPath + "/lawDemoDoc/" + filename));

                byte[] temp = new byte[1024];
                int len = 0;
                while((len = reader.read(temp)) != -1){
                    Log.i("长度",len + "");
                    writer.write(temp);
                }
                Toast.makeText(LawsRegulations.this,"上传成功",Toast.LENGTH_SHORT).show();
                //成功后刷新页面
                fileList.clear();
                findFiles();
                adapter.notifyDataSetChanged();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    writer.flush();
                    writer.close();
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //重写返回函数
    @Override
    public void onBackForwardClick(View v) {
        finish();
    }

    //扫描文件夹文件-----测试用
    private void findFiles(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdPath = Environment.getExternalStorageDirectory();
            File temp = new File(sdPath + "/lawDemoDoc");
            if(!temp.exists()){
                temp.mkdirs();
            }
            File[] files = temp.listFiles();
            for (File f : files) {
                String name = f.getName();
                String type = name.substring(name.indexOf(".") + 1,name.length());
                if(type.equals("doc") || type.equals("xls") || type.equals("pdf") || type.equals("docx")||type.equals("xlsx") ){
                    fileList.add(f);
                }
            }
        }else{
            Toast.makeText(this,"请检查sd卡",Toast.LENGTH_SHORT).show();
        }

    }




    class fileListAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return fileList.size();
        }

        @Override
        public Object getItem(int i) {
            return fileList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = LayoutInflater.from(LawsRegulations.this).inflate(R.layout.file_list_item,null);
            TextView tv = view.findViewById(R.id.tv_fileName);
            ImageView img = view.findViewById(R.id.img_fileIcon);
            //TextView trash = view.findViewById(R.id.tv_trash);
            //trash.setText(MDFonts.Trash);
            //trash.setTextSize(20);
            //MDFontsUtils.setOcticons(trash);
            String name = fileList.get(i).getName();
            String type = name.substring(name.indexOf(".") + 1, name.length());
            if(type.equals("doc") || type.equals("docx")){
                img.setImageResource(R.drawable.word);
            }else if(type.equals("pdf")){
                img.setImageResource(R.drawable.pdf);
            }else if(type.equals("xls") || type.equals("xlsx")){
                img.setImageResource(R.drawable.xls);
            }
            tv.setText(name);

            return view;
        }
    }

    class fileChoose implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            // 点击预览
            File readFile = fileList.get(i);
            FileChooseUtils.openFileByPath(getApplicationContext(),readFile.getAbsolutePath());
        }
    }

}



